package fr.migo.quisonne.android;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.provider.Contacts;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class QuiSonneListener extends PhoneStateListener{

	private Context mContext;

	private SharedPreferences mSharedPreferences;

	private final static String PREF_DEBUG="pref_debug";

	private final static String PREF_CONTACT_EXCEPT="pref_contacts";

	private Toast currentToast;
	
	public QuiSonneListener(Context context) {
		this.mContext=context;
		this.mSharedPreferences=PreferenceManager.getDefaultSharedPreferences(mContext);
	}
	
	@Override
	public void onCallStateChanged(int state, String incomingNumber) {

		super.onCallStateChanged(state, incomingNumber);

		switch (state) {

		case TelephonyManager.CALL_STATE_RINGING:
			
			boolean contactException = mSharedPreferences.getBoolean(PREF_CONTACT_EXCEPT, true);

			boolean isAContact = isAContact(incomingNumber);

			if(isAContact==false || contactException==false){
				currentToast=Toast.makeText(mContext, "Loading...", Toast.LENGTH_LONG);
				currentToast.show();
			}
			
			if(incomingNumber.startsWith("+33")){
				incomingNumber="0"+incomingNumber.substring(3);
				isAContact=isAContact(incomingNumber);
			}

			if(isAContact==false || contactException==false){
				currentToast=Toast.makeText(mContext, getInfos(incomingNumber), Toast.LENGTH_LONG);
				currentToast.show();
			}
			
			break;

		default:
			
			System.out.println(state+"   "+currentToast);
			if(currentToast!=null) currentToast.cancel();
			break;
		}
	}

	public boolean isAContact (String number){

		Cursor cursor=mContext.getContentResolver().query(Contacts.Phones.CONTENT_URI, null,  Contacts.Phones.NUMBER+"='"+number+"'",null, null);
		int count=cursor.getCount();
		cursor.close();

		return count > 0;
	}

	public String getInfos (String incomingNumber){

		DefaultHttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter("http.connection.timeout", new Integer(5000));

		StringBuilder url=new StringBuilder("http://iphone.pagesjaunes.fr/iphone/rechercheInverse.do?cID=2&numero=");
		url.append(Uri.encode(incomingNumber));

		HttpGet  httpget= new HttpGet(url.toString());
		httpget.setHeader("User-Agent", "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3"); 

		String error;

		try {

			HttpResponse response= httpclient.execute(httpget);

			StatusLine statusLine=response.getStatusLine();

			if(statusLine.getStatusCode()==HttpStatus.SC_OK){

				HttpEntity entity = response.getEntity();

				StringBuilder builder=new StringBuilder();

				Scanner scanner=new Scanner(entity.getContent(),"ISO-8859-1");
				while(scanner.hasNextLine())
					builder.append(scanner.nextLine());

				Pattern pattern=Pattern.compile(".*<span class=\"N3_parution_raison\">([^<]*).*");

				Matcher matcher=pattern.matcher(builder.toString());

				if(matcher.matches() && matcher.groupCount()==1 )
					return matcher.group(1).trim();
				return mContext.getString(R.string.number_unknown);
			}
			else
				error=statusLine.getReasonPhrase();

		}	catch (Exception e) {
			error=e.getLocalizedMessage();
		}  

		if(mSharedPreferences.getBoolean(PREF_DEBUG, false))
			return mContext.getString(R.string.number_not_found)+"\ndebug : "+error;
		return mContext.getString(R.string.number_not_found);
	}
}
